package cn.com.ahao.gateway.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static org.springframework.cloud.gateway.filter.NettyWriteResponseFilter.WRITE_RESPONSE_FILTER_ORDER;

@Component
public class HttpHeaderInfoFilter implements GlobalFilter, Ordered {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        logger.info("====== HttpHeaderInfoFilter start ======");
        ServerHttpRequest request = exchange.getRequest();
        logger.info("path: {}", request.getPath());
        HttpHeaders headers = request.getHeaders();
//        for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
//            if (entry.getValue() != null) {
//                String value = entry.getValue().stream().collect(Collectors.joining(","));
//                logger.info("entry: {}, value: {}.", entry.getKey(), value);
//            } else {
//                logger.info("entry: {}, value is null.", entry.getKey());
//            }
//        }
        return chain.filter(exchange).doFinally(t -> doFinally(exchange));
    }

    private void doFinally(ServerWebExchange exchange) {
        logger.info("====== HttpHeaderInfoFilter end ======");
    }

    @Override
    public int getOrder() {
        return WRITE_RESPONSE_FILTER_ORDER + 1;
    }
}
